<!-- 盛期调查 -->
<template>
	<view class="container">


		<view class="example">
			<!-- 基础用法，不包含校验规则 -->
			<uni-forms ref="baseForm" class="form-box" :model="surveydata" labelWidth="180rpx">
				<uni-forms-item label="监测站点代码" required>
					<uni-easyinput v-model="surveydata.ydNumber" :disabled="isnew" />
				</uni-forms-item>
				<uni-forms-item label="项目名称" required>
					<uni-easyinput v-model="surveydata.projectName" :disabled="true" />
				</uni-forms-item>
				<uni-forms-item label="行政区划">
					<uni-data-picker v-model="surveydata.city" @change="cityChange" class="cityWidth" :disabled="!isnew"
						:localdata="cityData" popup-title="选择城市">
					</uni-data-picker>
				</uni-forms-item>
				<uni-forms-item label="经度" required>
					<uni-easyinput v-model="surveydata.longitude" :disabled="!isnew" />
				</uni-forms-item>
				<uni-forms-item label="纬度" required>
					<uni-easyinput v-model="surveydata.latitude" :disabled="!isnew" />
				</uni-forms-item>
				<uni-forms-item label="海拔">
					<uni-easyinput v-model="surveydata.altitude" :disabled="!isnew" placeholder="请输入海拔" />
				</uni-forms-item>
				<uni-forms-item label="草地类型">
					<!-- <uni-data-picker v-model="surveydata.grasslandType" :disabled="!isnew" :localdata="grasslandType"
						popup-title="选择草地类型">
					</uni-data-picker> -->
					<niceui-data-select-input v-model="surveydata.grasslandType" :disabled="!isnew"
						:localdata="grasslandType" placeholder="请设置草地类型"></niceui-data-select-input>

				</uni-forms-item>
				<uni-forms-item label="土壤类型">
					<uni-data-picker v-model="surveydata.soilType" :disabled="!isnew" :localdata="soilType"
						popup-title="选择土壤类型">
					</uni-data-picker>
				</uni-forms-item>
				<uni-forms-item label="地形">
					<uni-data-picker v-model="surveydata.landform" :disabled="!isnew" :localdata="landform"
						popup-title="选择地形">
					</uni-data-picker>
				</uni-forms-item>
				<uni-forms-item label="调查人员">
					<uni-easyinput v-model="surveydata.surveyName" :disabled="true" />
				</uni-forms-item>
				<uni-forms-item label="调查时间">
					<uni-datetime-picker type="datetime" return-type="timestamp" :disabled="!isnew" @change="dateChange"
						format="yyyy-MM-dd" v-model="surveydata.createTime" />
				</uni-forms-item>
				<uni-forms-item label="样地照片" class="uni-list list-pd">
					<view class="uni-list-cell cell-pd">
						<view class="uni-uploader">
							<view class="uni-uploader-body">
								<view class="uni-uploader__files">
									<block v-for="(image,index) in imageList" :key="index">
										<view class="uni-uploader__file">
											<image class="uni-uploader__img" :src="image" :data-src="image"
												@tap="previewImage"></image>
										</view>
									</block>
									<view class="uni-uploader__input-box">
										<view class="uni-uploader__input" @tap="chooseImage"></view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</uni-forms-item>
				<uni-forms-item label="备注">
					<uni-easyinput type="textarea" v-model="surveydata.khqbz" placeholder="请输入自我介绍" />
				</uni-forms-item>

			</uni-forms>
			<button type="primary" @click="submit('valiForm')">{{title}}</button>

		</view>
		<view class="totopindex" @click="creatsquare">创建</br>样方</view>

	</view>
</template>

<script>
	import {
		getInfo,
		setInfo
	} from '@/core/unicommon/storyageInfo.js'
	import {
		addOrUpdateYd
	} from '@/api/system.js'
	import {
		saveImage,
		uploadImage
	} from '@/core/file/File.js'
	import {
		getLocation
	} from '@/core/unicommon/deviceInfo.js'
	export default {

		data() {
			return {
				isnew: false,
				type: 'edit',
				title: "提交",
				submited: false,
				sourceTypeIndex: 2,
				sourceType: ['拍照', '相册', '拍照或相册'],
				sizeTypeIndex: 2,
				sizeType: ['压缩', '原图', '压缩或原图'],
				countIndex: 8,
				count: [1, 2, 3, 4, 5, 6, 7, 8, 9],
				// 基础表单数据
				surveydata: {
					"address": "",
					"altitude": "",
					"city": 0,
					"cityName": "",
					"county": 0,
					"countyName": "",
					"createTime": new Date(),
					"createUser": "",
					"fileName": "",
					"fileUploadTime": "",
					"finishStatus": 0,
					"fqqbz": "",
					"fqqzp": "",
					"futu": "",
					"gclx": "",
					"grasslandType": "",

					"isDelete": 0,
					"jjxjs": "",
					"khqbz": "",
					"khqzp": "",
					"landform": "",
					"latitude": "",
					"longitude": "",
					"lsfg": "",
					"lyfs": "",
					"lyzk": "",
					"manageUser": "",
					"note": "",
					"podu": "",
					"powei": "",
					"poxiang": "",
					"projectName": "",
					"province": 0,
					"provinceName": "",
					"shuishi": "",
					"soilType": "",
					"sqbz": "",
					"sqzp": "",
					"status": 0,
					"surveyType": "枯黄期",
					"surveyUser": "",
					"town": 0,
					"townName": "",
					"updateTime": "2023-12-06T13:40:05.131Z",
					"village": 0,
					"villageName": "",
					"wljm": "",
					"ydNumber": ""

				},
				imageList: [],
				// 城市数据
				cityData: [],
				gravel: [],


				// 单选数据源
				ishas: [{
					text: '有',
					value: 0
				}, {
					text: '无',
					value: 1
				}],

				// 校验表单数据
				valiFormData: {
					name: '',
					age: '',
					introduction: '',
				},
				// 校验规则
				rules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '姓名不能为空'
						}]
					},
					age: {
						rules: [{
							required: true,
							errorMessage: '年龄不能为空'
						}, {
							format: 'number',
							errorMessage: '年龄只能输入数字'
						}]
					}
				},

			}
		},
		computed: {

		},
		onLoad(e) {
			if (e && e.data) {
				let data = JSON.parse(decodeURIComponent(e.data))
				if (data.action == 'creat') {
					this.surveydata = this.createObject()
					this.surveydata.action = data.action
					this.surveydata.grasslandType = "人工草地"
					this.surveydata.projectName = data.projectName
					this.surveydata.surveyType = data.surveyType
					this.isnew = true
					this.surveydata.createTime = new Date()
					this.surveydata.surveytime = new Date()
					this.submited = false
					this.title = "提交"
				} else {
					this.surveydata = data
					this.isnew = false
					this.title = "编辑"
					this.surveydata.updateTime = new Date()
					this.surveydata.surveytime = this.surveydata.createTime
					this.submited = true

				}


			}
			getInfo("userdata").then(res => {
				this.userdata = res.data

				function serialization(data) {
					// organizationName as text,organizationCode as value,childOrganization as children
					let orgs = []
					data.map(d => {
						let org = {
							text: d.organizationName,
							value: d.num > 3 ? d.organizationName : d.id,
							code: d.organizationCode,
							children: d.childOrganization && d.childOrganization.length > 0 ?
								serialization(d.childOrganization) : []
						}
						orgs.push(org)
					})
					return orgs

				}
				this.cityData = serialization(this.userdata.org)

				console.log("11", this.surveydata)
				let xzqh = []
				if (this.surveydata.province) {
					let orgProvince = this.userdata.org.find(t => t.id == this.surveydata.province)
					let province = {
						text: orgProvince.organizationName,
						value: this.surveydata.province
					}
					xzqh.push(province)

					if (this.surveydata.city) {
						let orgCity = orgProvince.childOrganization.find(t => t.id == this.surveydata.city)
						let city = {
							text: orgCity.organizationName,
							value: this.surveydata.city
						}
						xzqh.push(city)
						if (this.surveydata.county) {
							let orgCounty = orgCity.childOrganization.find(t => t.id == this.surveydata.county)
							let county = {
								text: orgCounty.organizationName,
								value: this.surveydata.county
							}
							xzqh.push(county)
							if (this.surveydata.town) {
								let orgTown = orgCounty.childOrganization.find(t => t.id == this.surveydata.town)
								if (orgTown) {
									let town = {
										text: orgTown.organizationName,
										value: this.surveydata.town
									}
									xzqh.push(town)
									if (this.surveydata.village) {
										let orgVillage = orgTown.childOrganization.find(t => t.id == this
											.surveydata.village)
										if (orgVillage) {
											let village = {
												text: orgVillage.organizationName,
												value: this.surveydata.village
											}
											xzqh.push(village)
										}

									}
								}

							}
						}
					}
				}
				this.surveydata.xzqh = xzqh

				let files = this.userdata.files
				this.imageList = []
				if (this.surveydata.khqzp) {
					let sqzp = JSON.parse(this.surveydata.khqzp)
					for (const zp of sqzp) {
						let localzp = files.find(t => t.type == 'yd' && t.uid == zp.uid)
						if (localzp) {
							this.imageList.push(localzp.localurl)
						}
					}
				}
				console.log("cityData", this.cityData, this.surveydata)
			})


			getInfo("userinfo").then(res => {
				this.surveydata.surveyName = res.data.nickname
				this.surveydata.surveyUser = res.data.id
			})
			// getInfo("network").then(res => {
			// 	this.network = res.data
			// })
			this.getNetWork()
			if (!this.surveydata.latitude || this.surveydata.latitude == '') {
				getLocation().then(res => {
					this.surveydata.longitude = res.longitude
					this.surveydata.latitude = res.latitude
				})
			}
			let resource = require("@/common/resource.json")
			this.grasslandType = resource.grasslandType
			this.poxiang = resource.poxiang
			this.soilType = resource.soilType
			this.landform = resource.landform
			this.gclx = resource.gclx
			this.gravel = resource.gravel
			this.ishas = resource.ishas
		},
		onReady() {
			this.getNetWork()
		},
		methods: {
			getNetWork() {
				let that = this
				uni.getNetworkType({
					success: res => {
						if (res.networkType === 'none') {
							that.network = false
						} else {
							that.network = true
						}
					}
				})
			},
			onNavigationBarButtonTap(e) {
				if (!this.submited) {
					return uni.showToast({
						title: '请先完成样地新建',
						icon: ''
					})
				}
				let item = this.surveydata
				uni.navigateTo({
					url: "/pages/sampleplot/samplesquare/squarelist?data=" + encodeURIComponent(JSON.stringify(
						item))
				});
			},
			cityChange(e) {
				let data = e.detail.value
				if (data[0]) {
					this.surveydata.province = data[0].value
					this.surveydata.provinceName = data[0].text
				}
				if (data[1]) {
					this.surveydata.city = data[1].value
					this.surveydata.cityName = data[1].text
				}
				if (data[2]) {
					this.surveydata.county = data[2].value
					this.surveydata.countyName = data[2].text
				}
				if (data[3]) {
					this.surveydata.town = data[3].value
					this.surveydata.townName = data[3].text
				}
				if (data[4]) {
					this.surveydata.village = data[4].value
					this.surveydata.villageName = data[4].text
				}
				if (this.isnew) {
					let num = ""
					let index = 0
					if (data[2]) {
						let dt = this.cityData.find(t => t.value == data[0].value).children.find(t => t.value == data[1]
							.value).children.find(t => t.value == data[2].value)
						let num = dt.code
						if (this.surveyYd.ydNumber.length <= 5) {
							this.surveydata.ydNumber = (new Date()).getFullYear() + "-" + num + "-" + (new Date())
							.getTime()
						}
					}
					// let arrs = this.cityData
					// data.forEach(d => {
					// 	let org = this.getcode(arrs, d.value)
					// 	num += (org.code + "").substring(index, 2)
					// 	console.log(org.code)
					// 	index += 2
					// 	arrs = org.children
					// })
					// this.surveydata.ydNumber = "2023-" + num + "-" + (new Date()).getTime()
					// console.log(this.surveydata.ydNumber.length)
				}

			},
			getcode(arrs, data) {
				let obj = arrs.find(t => t.value == data)
				return obj
			},

			creatsquare() {
				if (!this.submited) {
					return uni.showToast({
						title: '请先完成样地新建',
						icon: ''
					})
				}
				let item = this.surveydata

				uni.navigateTo({
					url: "/pages/sampleplot/samplesquare/yellowSquare?data=" + encodeURIComponent(JSON.stringify(
						item))
				});
			},
			isFullImg() {
				return new Promise((res) => {
					uni.showModal({
						content: "已经有9张图片了,是否清空现有图片？",
						success: (e) => {
							if (e.confirm) {
								this.imageList = [];
								res(true);
							} else {
								res(false)
							}
						},
						fail: () => {
							res(false)
						}
					})
				})
			},

			async chooseImage() {
				if (!this.isnew) {
					return
				}
				// #ifdef APP-PLUS
				// TODO 选择相机或相册时 需要弹出actionsheet，目前无法获得是相机还是相册，在失败回调中处理
				if (this.sourceTypeIndex !== 2) {
					let status = await this.checkPermission();
					if (status !== 1) {
						return;
					}
				}
				// #endif

				if (this.imageList.length === 9) {
					let isContinue = await this.isFullImg();
					console.log("是否继续?", isContinue);
					if (!isContinue) {
						return;
					}
				}
				uni.chooseImage({
					sourceType: ['camera', 'album'],

					count: this.imageList.length + this.count[this.countIndex] > 9 ? 9 - this.imageList
						.length : this.count[this.countIndex],
					success: (res) => {
						this.imageList = this.imageList.concat(res.tempFilePaths);
					},
					fail: (err) => {
						console.log("err: ", err);
						// #ifdef APP-PLUS
						if (err['code'] && err.code !== 0 && this.sourceTypeIndex === 2) {
							this.checkPermission(err.code);
						}
						// #endif
						// #ifdef MP
						if (err.errMsg.indexOf('cancel') !== '-1') {
							return;
						}
						uni.getSetting({
							success: (res) => {
								let authStatus = false;
								switch (this.sourceTypeIndex) {
									case 0:
										authStatus = res.authSetting['scope.camera'];
										break;
									case 1:
										authStatus = res.authSetting['scope.album'];
										break;
									case 2:
										authStatus = res.authSetting['scope.album'] && res
											.authSetting['scope.camera'];
										break;
									default:
										break;
								}
								if (!authStatus) {
									uni.showModal({
										title: '授权失败',
										content: 'Hello uni-app需要从您的相机或相册获取图片，请在设置界面打开相关权限',
										success: (res) => {
											if (res.confirm) {
												uni.openSetting()
											}
										}
									})
								}
							}
						})
						// #endif
					}
				})
			},
			previewImage: function(e) {
				var current = e.target.dataset.src
				uni.previewImage({
					current: current,
					urls: this.imageList
				})
			},
			async checkPermission(code) {
				console.log("code", code)
				let type = code ? code - 1 : this.sourceTypeIndex;
				let status = permision.isIOS ? await permision.requestIOS(sourceType[type][0]) :
					await permision.requestAndroid(type === 0 ? 'android.permission.CAMERA' :
						'android.permission.READ_EXTERNAL_STORAGE');

				if (status === null || status === 1) {
					status = 1;
				} else {
					uni.showModal({
						content: "没有开启权限",
						confirmText: "设置",
						success: function(res) {
							if (res.confirm) {
								permision.gotoAppSetting();
							}
						}
					})
				}
				return status;
			},


			createObject() {
				return {
					"address": "",
					"altitude": "",
					"city": 0,
					"cityName": "",
					"county": 0,
					"countyName": "",
					"createTime": new Date(),
					"createUser": "",
					"fileName": "",
					"fileUploadTime": "",
					"finishStatus": 0,
					"fqqbz": "",
					"fqqzp": "",
					"futu": "",
					"gclx": "",
					"grasslandType": "",

					"isDelete": 0,
					"jjxjs": "",
					"khqbz": "",
					"khqzp": "",
					"landform": "",
					"latitude": "",
					"longitude": "",
					"lsfg": "",
					"lyfs": "",
					"lyzk": "",
					"manageUser": "",
					"note": "",
					"podu": "",
					"powei": "",
					"poxiang": "",
					"projectName": "",
					"province": 0,
					"provinceName": "",
					"shuishi": "",
					"soilType": "",
					"sqbz": "",
					"sqzp": "",
					"status": 0,
					"surveyTime": "",
					"surveyType": "枯黄期",
					"surveyUser": "",
					"surveyUserName": "",
					"town": 0,
					"townName": "",
					"updateTime": "",
					"village": 0,
					"villageName": "",
					"wljm": "",
					"ydNumber": (new Date()).getFullYear() + '-',
					"yszb": ""
				}
			},



			submit() {
				if (this.title == "提交") {
					uni.showLoading({
						title: "提交中",
						mask: true,
						icon: 'loading',
					})
					if (this.network) {
						this.surveydata.action = 'none'

					} else {
						if (this.surveydata.action == 'none') {
							this.surveydata.action = 'edit'
						}
					}

					//缓存
					this.saveLocal().then(res => {
						if (this.network) {
							//提交
							addOrUpdateYd(this.surveydata).then(res => {
								uni.hideLoading()
								uni.showToast({
									title: '保存成功',
									icon: 'checkmarkempty'
								})
								this.title = "编辑"
							})
						} else {
							uni.hideLoading()
							uni.showToast({
								title: '无网络,数据缓存成功',
								icon: 'checkmarkempty'
							})
							this.title = "编辑"
						}
						this.submited = true
					})

				} else {
					this.title = "提交"
					this.isnew = true
				}

			},
			dateChange(e) {
				if (this.isNew) {
					this.surveydata.createTime = new Date(e)
					this.surveydata.updateTime = new Date(e)
				} else {
					this.surveydata.updateTime = new Date(e)
				}
			},
			async saveLocal() {
				let that = this
				let userdatares = await getInfo("userdata")
				let userdata = userdatares.data
				let peakPeriodzp = []
				for (const img of this.imageList) {
					let saveres = await saveImage(img)
					let upimages = {}
					if (that.network) {
						let res = await uploadImage(saveres.savedFilePath)
						if (res) {
							upimages = JSON.parse(res).data || {}
						}
					}
					let imgInfo = {
						name: '枯黄期调查',
						uid: upimages.name || (new Date()).getTime(),
						url: upimages.url || null,
						localurl: saveres.savedFilePath,
						id: (new Date()).getTime(),
						action: "edit",
						type: 'yd',
						ydNumber: that.surveydata.ydNumber,
						yfNumber: null
					}
					peakPeriodzp.push(imgInfo)
				}
				userdata.files = userdata.files.concat(peakPeriodzp)
				this.surveydata.khqzp = JSON.stringify(peakPeriodzp)

				let yd = userdata.yd
				if (this.surveydata.id) {
					let index = yd.findIndex(t => t.id == this.surveydata.id)

					yd[index] = this.surveydata
					userdata.yd = yd
				} else {
					yd.push(this.surveydata)
					userdata.yd = yd
				}
				setInfo("userdata", userdata)


			}



		}
	}
</script>

<style lang="scss" scoped>
	.container {
		position: absolute;
		width: 100vw;
		height: 100vh;

	}

	.example {
		position: absolute;
		width: 100%;
		height: 100vh;
		overflow-y: auto;

		background-color: #fff;
	}

	.form-box {
		padding: 15px;
	}

	.segmented-control {
		margin-bottom: 15px;
	}



	.totopindex {
		position: absolute;
		width: 100rpx;
		height: 100rpx;
		border-radius: 50rpx;
		background-color: #007aff;
		text-align: center;
		color: #fff;
		line-height: 45rpx;
		bottom: 120rpx;
		right: 20rpx;
	}

	// .cityWidth {
	// 	width: calc(100% - 180rpx);
	// 	// overflow-x: auto;
	// 	text-overflow: ellipsis;
	// 	-webkit-line-clamp: 3;
	// 	/*设置多少行*/
	// 	-webkit-box-orient: vertical;
	// 	/*必须结合的属性,设置或检索伸缩盒对象的子元素的排列方式*/
	// 	overflow: hidden;
	// 	/*文本会被修剪，并且剩余的部分不可见*/
	// 	text-overflow: ellipsis;
	// 	/*显示省略号来代表被修剪的文本*/
	// }
	::v-deep .uni-forms-item__content {
		width: calc(100% - 210rpx);
	}

	.button {
		display: flex;
		align-items: center;
		height: 35px;
		line-height: 35px;
		margin-left: 10px;
	}
</style>